package com.ctsi.djcloudmqtt.util.secure;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;

import java.io.UnsupportedEncodingException;

public class AESUtil {

    private static final String AES_KEY_SEED = "@#…………&￥#…………&&￥##";
    private static final String AES_KEY = "1c16cc87a14b624e781e492d92deacbf";

    /**
     * Aes加密后再base64加密
     *
     * @param data
     * @return
     */
    public static String Base64AesEncrypt(String data) {
        return Base64.encode(AESUtil.aesEncrypt(data));
    }

    /**
     * 先base64解密再aes解密
     *
     * @param byteAesData
     * @return
     */
    public static String Base64AesDecrypt(String byteAesData) {
        return AESUtil.aesDecrypt(Base64.decode(byteAesData));
    }

    /**
     * AES加密
     *
     * @param data
     * @return
     */
    public static byte[] aesEncrypt(String data) {
        AES aes = SecureUtil.aes(AES_KEY.getBytes());
        return aes.encrypt(data);
    }


    /**
     * AES解密
     *
     * @param secureData
     * @return
     */
    public static String aesDecrypt(byte[] secureData) {
        AES aes = SecureUtil.aes(AES_KEY.getBytes());
        try {
            return new String(aes.decrypt(secureData), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据密钥种子生成密钥
     *
     * @return
     */
    public static String generateKey() {
        return SecureUtil.md5(AES_KEY_SEED);
    }


    public static void main(String[] args) {
        System.out.println("加密密钥:" + AESUtil.generateKey());
        String data = "你好，世界，Java,31415926";
        System.out.println("AES加密前:" + data);
        byte[] byteAesData = AESUtil.aesEncrypt(data);
        System.out.println("AES加密后:" + byteAesData.toString());
        String base64AesData = Base64.encode(byteAesData);
        System.out.println("AES加密再转base64后:" + base64AesData);

        byteAesData = Base64.decode(base64AesData);
        System.out.println("base64解密:" + byteAesData);
        data = AESUtil.aesDecrypt(byteAesData);
        System.out.println("AES解密后:" + data);


        base64AesData = AESUtil.Base64AesEncrypt(data);
        System.out.println("AES加密再Base64加密:" + base64AesData);

        data = AESUtil.Base64AesDecrypt(base64AesData);
        System.out.println("Base64解密再AES解密:" + data);
    }

}
